package com.fitness.servlet;
import com.fitness.dao.ConsumptionDAO;
import com.fitness.entity.Consumption;
import com.fitness.dao.MemberDAO;
import com.fitness.dao.ProjectDAO;
import com.fitness.entity.Member;
import com.fitness.entity.Project;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/ConsumptionServlet")
public class ConsumptionServlet extends HttpServlet {
    private final ConsumptionDAO consumptionDAO = new ConsumptionDAO();
    private final MemberDAO memberDAO = new MemberDAO();
    private final ProjectDAO projectDAO = new ProjectDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        // 显示所有消费记录
        if ("list".equals(action)) {
            List<Consumption> consumptionList = consumptionDAO.getAllConsumptions();
            request.setAttribute("consumptionList", consumptionList);
            request.getRequestDispatcher("/WEB-INF/views/admin/consumptionList.jsp").forward(request, response);
        }
        // 删除消费记录
        else if ("delete".equals(action)) {
            try {
                int consumptionId = Integer.parseInt(request.getParameter("consumptionId"));
                boolean success = consumptionDAO.deleteConsumptionById(consumptionId);

                if (success) {
                    request.setAttribute("message", "删除成功");
                } else {
                    request.setAttribute("error", "删除失败");
                }

                response.sendRedirect("ConsumptionServlet?action=list");
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "删除操作出错");
                request.getRequestDispatcher("/WEB-INF/views/admin/consumptionList.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        // 添加消费记录
        if ("add".equals(action)) {
            try {
                int memberId = Integer.parseInt(request.getParameter("memberId"));
                int projectId = Integer.parseInt(request.getParameter("projectId"));
                String consumeTimeStr = request.getParameter("consumeTime");

                // 验证参数
                if (memberDAO.getMemberById(memberId) == null) {
                    request.setAttribute("error", "会员ID不存在");
                } else if (projectDAO.getProjectById(projectId) == null) {
                    request.setAttribute("error", "项目ID不存在");
                } else if (consumeTimeStr == null || consumeTimeStr.isEmpty()) {
                    request.setAttribute("error", "请选择消费时间");
                } else {
                    // 创建消费记录对象
                    Consumption consumption = new Consumption();
                    consumption.setMemberId(memberId);
                    consumption.setProjectId(projectId);
                    consumption.setConsumeTime(Timestamp.valueOf(consumeTimeStr.replace("T", " ") + ":00"));

                    // 插入数据库（触发器自动填充其他字段）
                    boolean success = consumptionDAO.insertConsumption(consumption);

                    if (success) {
                        request.setAttribute("message", "消费记录添加成功");
                    } else {
                        request.setAttribute("error", "添加失败，请重试");
                    }
                }

                // 重新查询消费记录列表
                List<Consumption> consumptionList = consumptionDAO.getAllConsumptions();
                request.setAttribute("consumptionList", consumptionList);
                request.getRequestDispatcher("/WEB-INF/views/admin/consumptionList.jsp").forward(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "添加操作出错：" + e.getMessage());
                request.getRequestDispatcher("/WEB-INF/views/admin/consumptionList.jsp").forward(request, response);
            }
        }
    }
}